--[[
Name: unitDoodles
Author: Sonora (The Dragonflight, US Kirin Tor)
Website & SVN: http://code.google.com/p/browniehelper/source/browse/#svn/trunk/unitDoodles
License: GNU General Public License v3
]]

--Runs in application namespace
setfenv(1, unitDoodles)

local function keys(t)
    ks = {}
    for k,_ in pairs(t) do table.insert(ks, k) end
    return ks
end

--[[
Simple OnUpdate task scheduler.

Factored out here to make it easy to plug in a smarter implementation if there
is a need.
]]
reactor = {
    calls = {},
    updateFrame = CreateFrame("Frame", "reactorFrame"),
    
    roundRobin = true,
    callList = {},
    
    start = function(self)
        self.updateFrame:SetScript('OnUpdate', function() self:update() end)
        self.updateFrame:Show() 
    end,
        
    stop = function(self) self.updateFrame:Hide() end,
    
    clear = function(self) self.calls = {} end,
    
    registerCall = function(self, call, interval)
        self.calls[call] = (interval and {interval=interval, lastFire=GetTime()} or true)
        self.callList = keys(self.calls)
    end,
    
    unregisterCall = function(self, call)
        if call then self.calls[call] = nil end
        self.callList = keys(self.calls)
    end,
    
    update = function(self)
        
        if self.roundRobin then
            if self.callIdx==nil or self.callList[self.callIdx]==nil then self.callIdx = 1 end
            
            local call = self.callList[self.callIdx]
            local timer = self.calls[call]
            if call~=nil then
                if timer == true then call()
                else
                    local currTime = GetTime()
                    if (timer.lastFire + timer.interval) < GetTime() then 
                        call()
                        timer.lastFire = GetTime()
                    end
                end
            end
            
            self.callIdx = self.callIdx+1
            
        else
            for call, timer in pairs(self.calls) do
                if timer == true then call()
                else
                    local currTime = GetTime()
                    if (timer.lastFire + timer.interval) < GetTime() then 
                        call()
                        timer.lastFire = GetTime()
                    end
                end
            end
        end
    
    end,
}
